import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import SystemUser from '../views/system/SystemUser.vue'
import SystemRole from '../views/system/SystemRole.vue'
import SystemConfig from '../views/system/SystemConfig.vue'
import SystemLog from '../views/system/SystemLog.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true },
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue'),
        meta: { requiresAuth: true, title: '控制台' }
      },
      {
        path: '/system/users',
        name: 'SystemUser',
        component: SystemUser,
        meta: { requiresAuth: true, title: '用户管理' }
      },
      {
        path: '/system/roles',
        name: 'SystemRole',
        component: SystemRole,
        meta: { requiresAuth: true, title: '角色权限' }
      },
      {
        path: '/system/configs',
        name: 'SystemConfig',
        component: SystemConfig,
        meta: { requiresAuth: true, title: '系统配置' }
      },
      {
        path: '/system/logs',
        name: 'SystemLog',
        component: SystemLog,
        meta: { requiresAuth: true, title: '操作日志' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const isLoggedIn = userStore.isLoggedIn

  // 如果路由需要认证
  if (to.meta.requiresAuth) {
    if (isLoggedIn) {
      next()
    } else {
      // 未登录，跳转到登录页
      next({ name: 'Login' })
    }
  } else {
    // 如果已登录且访问登录页，跳转到首页
    if (to.name === 'Login' && isLoggedIn) {
      next({ name: 'Home' })
    } else {
      next()
    }
  }
})

export default router

